import { ref, watch, onMounted } from 'vue'

export default function useTheme() {
  const theme = ref<'light' | 'dark'>('light')
  
  // 切换主题
  function toggleTheme() {
    theme.value = theme.value === 'light' ? 'dark' : 'light'
    applyTheme(theme.value)
    // 保存到本地存储
    localStorage.setItem('theme', theme.value)
  }
  
  // 应用主题到DOM
  function applyTheme(newTheme: 'light' | 'dark') {
    document.documentElement.setAttribute('data-theme', newTheme)
  }
  
  // 初始化主题
  function initTheme() {
    // 从localStorage读取保存的主题
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null
    if (savedTheme) {
      theme.value = savedTheme
    }
    applyTheme(theme.value)
  }
  
  // 在组件挂载时初始化主题
  onMounted(() => {
    initTheme()
  })
  
  return { theme, toggleTheme }
}